import Vue from 'vue'
import Vuex from 'vuex'
import { userInfoAPI } from '@/api/user'
import user from './modules/user'

Vue.use(Vuex)

import { saveToken, getToken, removeToken } from '@/utils/token'
import { Toast } from 'vant'
import router from '@/router'
export default new Vuex.Store({
  state: {
    tokenObj: getToken() || {},
    userinfo: {}
  },
  mutations: {
    setToken(state, obj) {
      state.tokenObj = obj
      saveToken(obj)
    },
    changeInfo(state, obj) {
      state.userinfo = obj
    },
    loginout(state) {
      state.tokenObj = {}
      state.userinfo = {}
      removeToken()
      Toast('退出成功')
      router.push('/login')
    }
  },
  actions: {
    async reqUserInfo(ctx) {
      if (!ctx.state.userinfo.name) {
        const res = await userInfoAPI()
        ctx.commit('changeInfo', res.data)
      }
    }
  },
  modules: {
    user
  }
})
